package be.sc.classicnetwork.util;

import java.awt.Image;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.ImageIcon;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.lf5.util.StreamUtils;

import be.sc.classicnetwork.exception.ApplicationException;

import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiException;
import com.sun.jimi.core.raster.JimiRasterImage;

/**
 * Misc Utils.
 */
public abstract class Utils {

	/** The default image given to a car if no image is uploaded */
	public static final String DEFAULT_IMAGE_PATH = "/image/noimage.gif";

	/** The banner image */
	public static final String BANNER_IMAGE_PATH = "/image/logo.gif";

	/**
	 * Convert.
	 */
	public static Integer[] convert(String[] sArray) {
		if (sArray == null)
			return null;

		ArrayList<Integer> ints = new ArrayList<Integer>();
		for (int i = 0; i < sArray.length; i++) {
			if (!NumberUtils.isDigits(sArray[i]))
				continue;
			ints.add(Integer.parseInt(sArray[i]));
		}
		return ints.toArray(new Integer[0]);
	}

	/**
	 * getDefaultImage.
	 */
	public static byte[] getDefaultImage() {
		try {
			return StreamUtils.getBytes(Utils.class
					.getResourceAsStream(DEFAULT_IMAGE_PATH));
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
	}

	/**
	 * getBannerImage.
	 */
	public static byte[] getBannerImage() {
		try {
			return StreamUtils.getBytes(Utils.class
					.getResourceAsStream(BANNER_IMAGE_PATH));
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
	}

	/**
	 * scale.
	 */
	public static byte[] scaleImage(byte[] image, int width) {
		Image inImage = new ImageIcon(image).getImage();

		// determine the scale
		double scale = (double) width / (double) inImage.getWidth(null);

		// Determine size of new image.
		int scaledW = (int) (scale * inImage.getWidth(null));

		// scale image
		Image scaledImage = inImage.getScaledInstance(scaledW, -1,
				Image.SCALE_SMOOTH);

		// return to output stream
		try {
			JimiRasterImage raster = Jimi.createRasterImage(scaledImage
					.getSource());
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			out.close();
			Jimi.putImage("image/jpeg", raster, out);
			return out.toByteArray();
		} catch (JimiException e) {
			throw new ApplicationException(e);
		} catch (IOException e) {
			throw new ApplicationException(e);
		}
	}

}
